package cn.intertion.service.impl;

import cn.intertion.dao.OperatorMapper;
import cn.intertion.model.Operator;
import cn.intertion.model.wxObj;
import cn.intertion.service.WXService;
import cn.intertion.utils.*;
import com.alibaba.fastjson.JSONObject;
import com.wf.captcha.Captcha;
import com.wf.captcha.GifCaptcha;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

import static io.lettuce.core.GeoArgs.Unit.m;

@Service
public class WXServiceImpl implements WXService {
    private static ArrayList codelist = new ArrayList();

    @Value("${wechatStatus}")
    private String wechatStatus;


    @Value("${ipaddr}")
    private String ipaddr;
    @Autowired
    private OperatorMapper operatorMapper;
    @Value("${tmpPath}")
    private String tmpPath;


    @Override
    public String addUser(HttpServletRequest req) throws Exception {
        String http2 = null;
        String code = req.getParameter("code");
        String state = req.getParameter("state");
        String mobile = state.split("@")[0];
        String duanxin = state.split("@")[1];
        String gongsi = state.split("@")[2];
        String username = state.split("@")[3];
        String email = state.split("@")[4];
        if (code != null && !code.equals("")) {
            String http8 = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                    + wxObj.appid + "&secret=" + wxObj.apppwd
                    + "&code=" + code + "&grant_type=authorization_code";
            String jsonStr = URLUtils.doGet(http8);
            String openid = JSONUtil.getString(jsonStr, "openid");
            //判断该openID是否已绑定
            http2 = ipaddr + "/a/c2?m=" + mobile + "&d=" + duanxin + "&g=" + gongsi + "&o=" + openid
                    + "&u=" + username + "&e=" + email+ "&w=" + wechatStatus;
        }
        String jsonStr = URLUtils.doGet(http2);
        if (jsonStr != null) {
            jsonStr = jsonStr.replace("\"", "");
            return jsonStr;
        }
        return "-1";
    }


    @Override
    public String bindWX(HttpServletRequest req) throws Exception {
        String code = req.getParameter("code");
        String str = req.getParameter("state");
        String mobile = str.split("@")[0];
        String yanzm = str.split("@")[1];
        String rtncode = URLUtils.doGet(ipaddr + "/w/chdx&s=" + yanzm);
        if (rtncode.replace("\"", "").equals("-1")) {
            return "-5";
        }
        if (code != null && !code.equals("")) {
            String http8 = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +
                    wxObj.appid + "&secret=" + wxObj.apppwd + "&code=" + code + "&grant_type=authorization_code";
            String jsonStr = URLUtils.doGet(http8);
            String openid = JSONUtil.getString(jsonStr, "openid");
            List<Operator> li = operatorMapper.selectByMobile(mobile);
            if (li == null || li.size() == 0) {
                //不存在
                return 1 + "";
            } else {
                //存在绑定openID
                Operator oo1 = li.get(0);
                String token = UUIDUtil.randomUUID8();
                oo1.setOpenid(openid);
                oo1.setVtoken(token);
                oo1.setVtokenTime(new Date());
                oo1.setWechatStatus(wechatStatus);
                operatorMapper.updateOpenidById(openid, token, new Date(), oo1.getId());
                return 2 + "#" + token;
            }
        }
        return -1 + "";
    }


    @Override
    public String regOrAdd(HttpServletRequest req) throws Exception {
        String code = req.getParameter("code");
        if (code != null && !code.equals("")) {
            String state = req.getParameter("state");
            String[] strs = state.split("@");
            String http8 = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + wxObj.appid + "&secret=" + wxObj.apppwd
                    + "&code=" + code + "&grant_type=authorization_code";
            String jsonStr = URLUtils.doGet(http8);
            String openid = JSONUtil.getString(jsonStr, "openid");
            String mobile = state.split("@")[0];
            String duanxin = state.split("@")[1];
            List<Operator> li = operatorMapper.selectByMobile(mobile);
            if (openid != null && !openid.equals("")) {
                if (li != null && li.size() > 0) {
//                    绑定
                    Operator oo1 = li.get(0);
                    String token = UUIDUtil.randomUUID8();
                    oo1.setOpenid(openid);
                    oo1.setVtoken(token);
                    oo1.setVtokenTime(new Date());
                    oo1.setWechatStatus(wechatStatus);
                    operatorMapper.updateOpenidById(openid, token, new Date(), oo1.getId());
                    return token;

                } else {
                    if (strs.length < 3) {
//                 请填写公司 船舶名
                        return "-9";
                    }
                    String gongsi = state.split("@")[2];
                    String username = state.split("@")[3];
                    String http2 = ipaddr + "/a/c2?m=" + mobile + "&d=" + duanxin + "&g=" + gongsi + "&o=" + openid
                            + "&u=" + username +  "&w=" + wechatStatus;
                    String jsonStr2 = URLUtils.doGet(http2);
                    if (jsonStr2 != null) {
                        jsonStr2 = jsonStr2.replace("\"", "");
                        return jsonStr2;
                    }
                }
            } else {
//                未知异常
                return "-7";
            }
        } else {
//            未知异常
            return "-7";
        }
        //            未知异常
        return "-7";
    }

    @Override
    public String login(String code, String state) throws Exception {
        String flag = "df54a4gvafas4";
        if (flag.equals(state)) {
            String http = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="
                    + wxObj.appid + "&secret=" + wxObj.apppwd + "&code=" + code + "&grant_type=authorization_code";
            String ss = URLUtils.doGet(http);
            String openid = JSONUtil.getString(ss, "openid");
            //当前请求合法
            String token = URLUtils.doGet(wxObj.ipinfo + openid+"&w="+wechatStatus);
            token = token.replace("\"", "");
            return token;
        }
//        用户不合法
        return "-2";
    }


    public void out(int width, int height, int len, HttpServletRequest request, HttpServletResponse response, String uid) throws IOException {
        setHeader(response);
        Captcha captcha = new GifCaptcha(width, height, len);
        String code = captcha.text().toLowerCase();
        if (codelist.size() > 100000) {
            clsCode();
        }
        codelist.add(uid.trim() + code.trim());
        request.getSession().setAttribute("captcha", code);
        captcha.out(response.getOutputStream());
    }

    @Override
    public void out2(String uid, HttpServletResponse resp) throws IOException {
        delTempFiles();
        String s = CaptchaUtil.randomUUID5();
        File f1 = new File(tmpPath);
        if (!f1.exists()) f1.mkdirs();
        long l = System.currentTimeMillis();
        ImageIO.write(CaptchaUtil.getCreateImg(s), "jpg", new File(tmpPath + l + ".jpg"));
        if (codelist.size() > 10000) {
            clsCode();
        }
        codelist.add(uid.trim() + s.trim().toLowerCase());
        resp.setContentType("image/jpg");
        resp.setHeader("Pragma", "No-cache");
        resp.setHeader("Cache-Control", "no-cache");
        resp.setDateHeader("Expires", 0L);
        OutputStream out = resp.getOutputStream();
        //将图刷出去
        File f2 = new File(tmpPath + l + ".jpg");
        out.write(IOUtils.toByteArray(new FileInputStream(f2)));
        out.flush();
        out.close();
    }

    private void delTempFiles() {
        File fff = new File(tmpPath);
        if (!fff.exists()) {
            fff.mkdirs();
        }
        File f2 = new File(tmpPath);
        File[] f3 = f2.listFiles();
        if (f3 != null) {
            for (File f4 : f3) {
                try {
                    f4.delete();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void setHeader(HttpServletResponse response) {
        response.setContentType("image/gif");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0L);
    }

    private void clsCode() {
        for (int i = 0; i < 5000; i++) {
            codelist.remove(i);
        }
    }

    @Override
    public Integer check2(String str) {
        if (codelist.contains(str)) {
            return 1;
        }
        return 0;
    }

    @Override
    public Integer check(String str) {
        if (codelist.contains(str)) {
            return 1;
        }
        return 0;
    }

    /*************************************微信jssdk获取*********************************************/
    @Override
    public String getJsSdkTicket(String url) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        Map<String, String> sign = sign(wxObj.jsSdk, url);
        JSONObject object = new JSONObject();
        object.put("timestamp", sign.get("timestamp"));
        object.put("noncestr", sign.get("nonceStr"));
        object.put("signature", sign.get("signature"));
        return object.toJSONString();
    }

    public static Map<String, String> sign(String jsapi_ticket, String url) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        MessageDigest crypt = MessageDigest.getInstance("SHA-1");
        crypt.reset();
        crypt.update(string1.getBytes("UTF-8"));
        signature = byteToHex(crypt.digest());
        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }


    /***************************************微信jssdk获取*******************************************/

    @Override
    public boolean checkUser(String name, String pswd) {
        List<Operator> li = operatorMapper.checkUser(name, pswd);
        return li != null && li.size() > 0;
    }

    /**
     * 用户注册发送短信验证码
     *
     * @param p 注册手机号
     */
    @Override
    public String sendShortmessage(String p) throws Exception {
        List<Operator> operators = operatorMapper.selectByMobile(p);
        String http2 = ipaddr + "/w/sm2?p=" + p;
        String str = URLUtils.doGet(http2);
        str = str.replace("\"", "");
        if (operators != null && operators.size() > 0) {
            return "-1#" + str;
        } else {
            return "0#" + str;
        }

    }

    @Override
    public String check3(String p) throws Exception {
        String http2 = ipaddr + "/w/chdx?s=" + p;
        String str = URLUtils.doGet(http2);
        str = str.replace("\"", "");

        return str;
    }


}
